package top.cptr.simpleRpc.rpccore;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * @author Tiger_L
 * @version 1.0
 * @description rpcItem
 * @date 2024/1/4 16:03
 */
@AllArgsConstructor
@NoArgsConstructor
public class RpcItem {
    private Object origin;

    private Method method;


    public Object handle(Object... args) {
        try {
            Class<?>[] parameterTypes = method.getParameterTypes();
            ArrayList<Object> params = new ArrayList<>();
            for (int i = 0; i < parameterTypes.length; i++) {
                Object re = JSON.parseObject(JSON.toJSONString(args[i]), parameterTypes[i]);
                params.add(re);
            }
            Object result = method.invoke(origin, params.toArray());
            return result;
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    protected static RpcItem build(Object origin, Method method) {
        return new RpcItem(origin, method);
    }
}
